package cn.weixindong.com.session;

import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.SerializationUtils;

import com.google.gson.Gson;

import cn.weixindong.com.redis.JedisClient;

public class RedisSessionDao extends AbstractSessionDAO {

	@Autowired
	private JedisClient jedisClient;

	private final String SESSION_PREFIX = "imocc-session";

	@Override
	public void update(Session session) throws UnknownSessionException {
		System.out.println("进入更新");
		saveMySession(session);

	}

	@Override
	public void delete(Session session) {
		System.out.println("进入删除");
		if(session!=null&&session.getId()!=null) {
			
			byte[] key = getKey(session.getId().toString());
			jedisClient.del(key);	
		}
		

	}

	@Override
	public Collection<Session> getActiveSessions() {
		System.out.println("获取所有session");
		Set<byte[]> keys = jedisClient.keys((SESSION_PREFIX+"*").getBytes());
		
		   if (CollectionUtils.isEmpty(keys)) {
			   
			   return Collections.emptySet();
			   
		   }
		HashSet<Session> hashSet = new HashSet<Session>();
		
		System.out.println(keys.size()+"哈哈");
		
		for (byte[] bs : keys) {
			System.out.println("进入");
			Session deserialize = (Session)SerializationUtils.deserialize(bs);
			hashSet.add(deserialize);
		}
		
		return hashSet;
	}

	@Override
	protected Serializable doCreate(Session session) {
		System.out.println("进入创造session方法");
		System.out.println(new Gson().toJson(session));
		System.out.println("sessionid为"+session.getId());
		Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);
        
        saveMySession(session);
		return sessionId;
	}

	@Override
	protected Session doReadSession(Serializable sessionId) {
		
		if(sessionId==null) {
			
			return null;
		}
		System.out.println("读取单个session");

			
			byte[] key = getKey(sessionId.toString());
			byte[] bs = jedisClient.get(key);
			
			if(bs==null) {
				return null;
			}
			System.out.println("获取的数据为"+bs.toString());
			return (Session) SerializationUtils.deserialize(bs);
		
	}

	private void saveMySession(Session session) {
		
		System.out.println("进入存储session方法"+session.getTimeout());
		if (session != null && session.getId() != null) {

			byte[] key = getKey(session.getId().toString());
			jedisClient.set(key, SerializationUtils.serialize(session));

			jedisClient.expire(key, 1700);

		}

	}

	private byte[] getKey(String key) {

		return (SESSION_PREFIX + key).getBytes();
	}

}
